<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>C/C++ 关于 cJson 库的使用 | 逝水无痕の博客</title><meta name="keywords" content="c++,cJson"><meta name="author" content="逝水无痕"><meta name="copyright" content="逝水无痕"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="C&#x2F;C++ 关于 cJson 库的使用关于 Json 这种数据格式，在前面已经做了详细的介绍 Json 的格式和用途，在项目开发过程中我们需要针对不同的语言使用不同的库对 Json 格式的数据进行解析，下面给大家介绍一个基于 C 语言的 Json 库 – cJson。cJSON 是一个超轻巧，携带方便，单文件，简单的可以作为 ANSI-C 标准的 JSON 解析器。 cJSON 是一个开源项目，g">
<meta property="og:type" content="article">
<meta property="og:title" content="C&#x2F;C++ 关于 cJson 库的使用">
<meta property="og:url" content="https://hexo.zyjblogs.cn/posts/c++/library/json/1.html">
<meta property="og:site_name" content="逝水无痕の博客">
<meta property="og:description" content="C&#x2F;C++ 关于 cJson 库的使用关于 Json 这种数据格式，在前面已经做了详细的介绍 Json 的格式和用途，在项目开发过程中我们需要针对不同的语言使用不同的库对 Json 格式的数据进行解析，下面给大家介绍一个基于 C 语言的 Json 库 – cJson。cJSON 是一个超轻巧，携带方便，单文件，简单的可以作为 ANSI-C 标准的 JSON 解析器。 cJSON 是一个开源项目，g">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg">
<meta property="article:published_time" content="2022-02-06T16:00:00.000Z">
<meta property="article:modified_time" content="2022-02-08T08:38:03.276Z">
<meta property="article:author" content="逝水无痕">
<meta property="article:tag" content="c++">
<meta property="article:tag" content="cJson">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg"><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="https://hexo.zyjblogs.cn/posts/c++/library/json/1"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//hm.baidu.com"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><script>var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?6edd69cc926242ec43e7194677fb8040";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#121212","position":"bottom-left"},
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isanchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'C/C++ 关于 cJson 库的使用',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2022-02-08 16:38:03'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if (GLOBAL_CONFIG_SITE.isHome && /iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    document.addEventListener('pjax:complete', detectApple)})(window)</script><link rel="stylesheet" href="_static/css/background.css"><meta name="generator" content="Hexo 5.4.0"><link rel="alternate" href="/atom.xml" title="逝水无痕の博客" type="application/atom+xml">
<link rel="alternate" href="/rss2.xml" title="逝水无痕の博客" type="application/rss+xml">
</head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="https://zyjblogs.cn/logo.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/archives/"><div class="headline">文章</div><div class="length-num">11</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/tags/"><div class="headline">标签</div><div class="length-num">8</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/categories/"><div class="headline">分类</div><div class="length-num">5</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 媒体</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/bangumis"><i class="fa-fw fa-fw fab fa-youtube"></i><span> 番剧</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">逝水无痕の博客</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 媒体</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/bangumis"><i class="fa-fw fa-fw fab fa-youtube"></i><span> 番剧</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">C/C++ 关于 cJson 库的使用</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2022-02-06T16:00:00.000Z" title="发表于 2022-02-07 00:00:00">2022-02-07</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2022-02-08T08:38:03.276Z" title="更新于 2022-02-08 16:38:03">2022-02-08</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/c/">c++</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">3.3k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>14分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="C/C++ 关于 cJson 库的使用"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="C-C-关于-cJson-库的使用"><a href="#C-C-关于-cJson-库的使用" class="headerlink" title="C/C++ 关于 cJson 库的使用"></a>C/C++ 关于 cJson 库的使用</h1><p>关于 Json 这种数据格式，在前面已经做了详细的介绍 Json 的格式和用途，在项目开发过程中我们需要针对不同的语言使用不同的库对 Json 格式的数据进行解析，下面给大家介绍一个基于 C 语言的 Json 库 – cJson。cJSON 是一个超轻巧，携带方便，单文件，简单的可以作为 ANSI-C 标准的 JSON 解析器。</p>
<p>cJSON 是一个开源项目，github 下载地址：</p>
<blockquote>
<p><a target="_blank" rel="noopener" href="https://github.com/DaveGamble/cJSON">https://github.com/DaveGamble/cJSON</a></p>
</blockquote>
<p>cJSON，目前来说，主要的文件有两个，一个 <code>cJSON.c</code> 一个 <code>cJSON.h</code>。使用的时候，将头文件 include 进去即可。</p>
<p>如果是在 Linux 操作系统中使用，编译 到时候需要添加数学库 <code>libm.so</code>，如下所示：</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">gcc  *.c  cJSON.c  -lm</span><br></pre></td></tr></table></figure>

<h2 id="1-cJSON-结构体"><a href="#1-cJSON-结构体" class="headerlink" title="1. cJSON 结构体"></a>1. cJSON 结构体</h2><p>在 <code>cJSON.h</code> 中定义了一个非常重要的结构体 cJSON，想要熟悉使用 cJSON 库函数可从 cJSON 结构体入手，cJSON 结构体如下所示：</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">typedef struct cJSON &#123;  </span><br><span class="line">     struct cJSON *next,*prev;   </span><br><span class="line">     struct cJSON *child;   </span><br><span class="line">     int type;   </span><br><span class="line">     char *valuestring;        // value值是字符串类型</span><br><span class="line">     int valueint;  </span><br><span class="line">     double valuedouble;   </span><br><span class="line">     char *string;             // 对象中的key</span><br><span class="line">&#125; cJSON; </span><br></pre></td></tr></table></figure>

<p>关于这个结构体做如下几点的说明:</p>
<ol>
<li>cJOSN 结构体是一个双向链表，并且可通过 child 指针访问下一层。</li>
<li>结构体成员 type 变量用于描述数据元素的类型（如果是键值对表示 value 值的类型），数据元素可以是字符串可以是整形，也可以是浮点型。</li>
</ol>
<ul>
<li>如果是整形值的话可通过 valueint 将值取出</li>
<li>如果是浮点型的话可通过 valuedouble 将值取出</li>
<li>如果是字符串类型的话可通过 valuestring 将值取出</li>
</ul>
<ol>
<li>结构体成员 string 表示键值对中键值的名称。</li>
</ol>
<p>cJSON 作为 Json 格式的解析库，其主要功能就是构建和解析 Json 格式了，比如要发送数据：用途就是发送端将要发送的数据以 json 形式封装，然后发送，接收端收到此数据后，还是按 json 形式解析，就得到想要的数据了。</p>
<h2 id="2-cJson-API"><a href="#2-cJson-API" class="headerlink" title="2. cJson API"></a>2. cJson API</h2><p>Json 格式的数据无外乎有两种 Json对象和 Json数组，创建的 Json 数据串可能是二者中 的一种，也可能是二者的组合，不管哪一种通过调用相关的 API 函数都可以轻松的做到这一点。</p>
<h3 id="2-1-数据的封装"><a href="#2-1-数据的封装" class="headerlink" title="2.1 数据的封装"></a>2.1 数据的封装</h3><p>在 <code>cJSON.h</code> 头文件中可以看到一些函数声明，通过调用这些创建函数就可以将 Json 支持的数据类型封装为 cJSON 结构体类型：</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">// 空值类型</span><br><span class="line">extern cJSON *cJSON_CreateNull(void);</span><br><span class="line">// 布尔类型</span><br><span class="line">extern cJSON *cJSON_CreateTrue(void);</span><br><span class="line">extern cJSON *cJSON_CreateFalse(void);</span><br><span class="line">extern cJSON *cJSON_CreateBool(int b);</span><br><span class="line">// 数值类型</span><br><span class="line">extern cJSON *cJSON_CreateNumber(double num);</span><br><span class="line">// 字符串类型</span><br><span class="line">extern cJSON *cJSON_CreateString(const char *string);</span><br><span class="line">// json数组(创建空数组)</span><br><span class="line">extern cJSON *cJSON_CreateArray(void);</span><br><span class="line">// json对象(创建空对象)</span><br><span class="line">extern cJSON *cJSON_CreateObject(void);</span><br></pre></td></tr></table></figure>

<p>另外，cJson 库中还给我我们提供了一些更为简便的操作函数，在创建数组的同时还可以进行初始化</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">// 创建一个Json数组, 元素为整形</span><br><span class="line">extern cJSON *cJSON_CreateIntArray(const int *numbers,int count);</span><br><span class="line">// 创建一个Json数组, 元素为浮点</span><br><span class="line">extern cJSON *cJSON_CreateFloatArray(const float *numbers,int count);</span><br><span class="line">extern cJSON *cJSON_CreateDoubleArray(const double *numbers,int count);</span><br><span class="line">// 创建一个Json数组, 元素为字符串类型</span><br><span class="line">extern cJSON *cJSON_CreateStringArray(const char **strings,int count);</span><br></pre></td></tr></table></figure>

<h3 id="2-2-Json-对象操作"><a href="#2-2-Json-对象操作" class="headerlink" title="2.2 Json 对象操作"></a>2.2 Json 对象操作</h3><p>当得到一个 Json 对象之后，就可以往对象中添加键值对了，可以使用 <code>cJSON_AddItemToObject()</code></p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">extern void cJSON_AddItemToObject(cJSON *object,const char *string,cJSON *item);</span><br></pre></td></tr></table></figure>

<p>在 cJSON 库中节点的从属关系是通过树来维护的，每一层节点都是通过链表来维护的，这样就能分析出该函数参数的含义：</p>
<ul>
<li>object：要添加的键值对从属于那个节点</li>
<li>string：添加的键值对的键值</li>
<li>item：添加的键值对的 value 值（需要先将其封装为 cJSON 类型的结构体）</li>
</ul>
<p>为了让我的操作更加方便，cJson 库还给我们提供了一些宏函数，方便我们快速的往 Json 对象中添加键值对</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">#define cJSON_AddNullToObject(object,name)      cJSON_AddItemToObject(object, name, cJSON_CreateNull())</span><br><span class="line">#define cJSON_AddTrueToObject(object,name)      cJSON_AddItemToObject(object, name, cJSON_CreateTrue())</span><br><span class="line">#define cJSON_AddFalseToObject(object,name)     cJSON_AddItemToObject(object, name, cJSON_CreateFalse())</span><br><span class="line">#define cJSON_AddBoolToObject(object,name,b)    cJSON_AddItemToObject(object, name, cJSON_CreateBool(b))</span><br><span class="line">#define cJSON_AddNumberToObject(object,name,n)  cJSON_AddItemToObject(object, name, cJSON_CreateNumber(n))</span><br><span class="line">#define cJSON_AddStringToObject(object,name,s)  cJSON_AddItemToObject(object, name, cJSON_CreateString(s))</span><br></pre></td></tr></table></figure>

<p>我们还可以根据 Json 对象中的键值取出相应的 value 值，API 函数原型如下:</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">extern cJSON *cJSON_GetObjectItem(cJSON *object,const char *string);</span><br></pre></td></tr></table></figure>

<h3 id="2-3-Json-数组操作"><a href="#2-3-Json-数组操作" class="headerlink" title="2.3 Json 数组操作"></a>2.3 Json 数组操作</h3><p>添加数据到 Json 数组中（原始数据需要先转换为 cJSON 结构体类型）</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">extern void cJSON_AddItemToArray(cJSON *array, cJSON *item);</span><br></pre></td></tr></table></figure>

<p>得到 Json 数组中元素的个数:</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">extern int cJSON_GetArraySize(cJSON *array);</span><br></pre></td></tr></table></figure>

<p>得到 Json 数组中指定位置的原素，如果返回 NULL 表示取值失败了。</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">extern cJSON *cJSON_GetArrayItem(cJSON *array,int item);</span><br></pre></td></tr></table></figure>

<h3 id="2-4-序列化"><a href="#2-4-序列化" class="headerlink" title="2.4 序列化"></a>2.4 序列化</h3><p>序列化就是将 Json 格式的数据转换为字符串的过程，cJson 库中给我们提供了 3 个转换函数，具体如下：</p>
<p>第一个参数 item 表示 Json 数据块的根节点。</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">extern char  *cJSON_Print(cJSON *item);</span><br><span class="line">extern char  *cJSON_PrintUnformatted(cJSON *item);</span><br><span class="line">extern char *cJSON_PrintBuffered(cJSON *item,int prebuffer,int fmt);</span><br></pre></td></tr></table></figure>

<ul>
<li>调用 <code>cJSON_Print()</code> 函数我们可以得到一个带格式的 Json 字符串（有换行，看起来更直观）</li>
<li>调用 <code>cJSON_PrintUnformatted()</code> 函数会得到一个没有格式的 Json 字符串（没有换行，所有的数据都在同一行）。</li>
<li>调用 <code>cJSON_PrintBuffered()</code> 函数使用缓冲策略将 Json 实体转换为字符串，参数 prebuffer 是指定缓冲区的大小，参数 <code>fmt==0</code> 表示未格式化，<code>fmt==1</code> 表示格式化。</li>
</ul>
<p>我们在编码过程中可以根据自己的实际需求调用相关的操作函数得到对应格式的 Json 字符串。</p>
<h3 id="2-5-Json-字符串的解析"><a href="#2-5-Json-字符串的解析" class="headerlink" title="2.5 Json 字符串的解析"></a>2.5 Json 字符串的解析</h3><p>如果我们得到了一个 Json 格式的字符串，想要读出里边的数据，就需要对这个字符串进行解析，处理方式就是将字符串转换为 cJSON 结构体，然后再基于这个结构体读里边的原始数据，转换函数的函数原型如下：</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">extern cJSON *cJSON_Parse(const char *value);</span><br></pre></td></tr></table></figure>

<h3 id="2-6-内存释放"><a href="#2-6-内存释放" class="headerlink" title="2.6 内存释放"></a>2.6 内存释放</h3><p>当我们将数据封装为 cJSON 结构类型的节点之后都会得到一块堆内存，当我们释放某个节点的时候可以调用 cJson 库提供的删除函数 <code>cJSON_Delete()</code>，函数原型如下：</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">extern void   cJSON_Delete(cJSON *c);</span><br></pre></td></tr></table></figure>

<p>该函数的参数为要释放的节点的地址，在此强调一点：在进行内存地址释放的时候，当前节点以及其子节点都会被删除。</p>
<h2 id="3-Json-数据的封装"><a href="#3-Json-数据的封装" class="headerlink" title="3. Json 数据的封装"></a>3. Json 数据的封装</h2><h3 id="3-1-Json-对象操作举例"><a href="#3-1-Json-对象操作举例" class="headerlink" title="3.1 Json 对象操作举例"></a>3.1 Json 对象操作举例</h3><blockquote>
<p>创建一个对象，并向这个对象里添加字符串和整型键值：</p>
</blockquote>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">#include&lt;stdio.h&gt;</span><br><span class="line">#include&lt;stdlib.h&gt;</span><br><span class="line">#include&lt;string.h&gt;</span><br><span class="line">#include&quot;cJSON.h&quot;</span><br><span class="line"> </span><br><span class="line">int main()</span><br><span class="line">&#123;</span><br><span class="line">    cJSON * root;</span><br><span class="line">    cJSON *arry;</span><br><span class="line"></span><br><span class="line">    root=cJSON_CreateObject();                     // 创建根数据对象</span><br><span class="line">    cJSON_AddStringToObject(root,&quot;name&quot;,&quot;luffy&quot;);  // 添加键值对</span><br><span class="line">    cJSON_AddStringToObject(root,&quot;sex&quot;,&quot;man&quot;);     // 添加键值对</span><br><span class="line">    cJSON_AddNumberToObject(root,&quot;age&quot;,19);        // 添加键值对</span><br><span class="line"></span><br><span class="line">    char *out = cJSON_Print(root);   // 将json形式转换成字符串</span><br><span class="line">    printf(&quot;%s\n&quot;,out);</span><br><span class="line"></span><br><span class="line">    // 释放内存  </span><br><span class="line">    cJSON_Delete(root);  </span><br><span class="line">    free(out);        </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>运行结果</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">&#123;</span><br><span class="line"> &quot;name&quot;: &quot;luffy&quot;,</span><br><span class="line"> &quot;sex&quot;: &quot;man&quot;,</span><br><span class="line"> &quot;age&quot;: 19</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>若干说明:</p>
<ul>
<li><code>cJSON_CreateObject</code> 函数可创建一个根对象，返回的是一个 cJSON 指针，在这个指针用完了以后，需要手动调用 <code>cJSON_Delete(root)</code> 进行内存回收。</li>
<li>函数 <code>cJSON_Print()</code> 内部封装了 malloc 函数，所以需要使用 free() 函数释放被 out 占用的内存空间。</li>
</ul>
<h3 id="3-2-Json-数组操作举例"><a href="#3-2-Json-数组操作举例" class="headerlink" title="3.2 Json 数组操作举例"></a>3.2 Json 数组操作举例</h3><blockquote>
<p>创建一个数组，并向数组添加一个字符串和一个数字</p>
</blockquote>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">int main(int argc, char **argv)</span><br><span class="line">&#123;</span><br><span class="line">    cJSON *root;</span><br><span class="line">    root = cJSON_CreateArray();</span><br><span class="line">    cJSON_AddItemToArray(root, cJSON_CreateString(&quot;Hello world&quot;));</span><br><span class="line">    cJSON_AddItemToArray(root, cJSON_CreateNumber(10)); </span><br><span class="line">    // char *s = cJSON_Print(root);</span><br><span class="line">    char *s = cJSON_PrintUnformatted(root);</span><br><span class="line">    if(s)</span><br><span class="line">    &#123;</span><br><span class="line">        printf(&quot; %s \n&quot;,s);</span><br><span class="line">        free(s);</span><br><span class="line">    &#125;</span><br><span class="line">    cJSON_Delete(root);</span><br><span class="line">    return 0;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>运行结果:</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">[&quot;Hello world&quot;,10]</span><br></pre></td></tr></table></figure>

<h3 id="3-3-Json-对象、数组嵌套使用"><a href="#3-3-Json-对象、数组嵌套使用" class="headerlink" title="3.3 Json 对象、数组嵌套使用"></a>3.3 Json 对象、数组嵌套使用</h3><blockquote>
<p>对象里面包括一个数组，数组里面包括对象，对象里面再添加一个字符串和一个数字</p>
</blockquote>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">&#123;</span><br><span class="line">    &quot;person&quot;:[&#123;</span><br><span class="line">        &quot;name&quot;:&quot;luffy&quot;,</span><br><span class="line">        &quot;age&quot;:19</span><br><span class="line">    &#125;]</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>示例代码:</p>
<figure class="highlight cpp"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">(<span class="keyword">int</span> argc, <span class="keyword">char</span> **argv)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    cJSON *root, *body, *list;</span><br><span class="line">    <span class="comment">// josn 对象 root</span></span><br><span class="line">    root = <span class="built_in">cJSON_CreateObject</span>();</span><br><span class="line">    <span class="comment">// root 添加键值对 person:json数组A</span></span><br><span class="line">    <span class="built_in">cJSON_AddItemToObject</span>(root,<span class="string">&quot;person&quot;</span>, body = <span class="built_in">cJSON_CreateArray</span>());</span><br><span class="line">    <span class="comment">// json数组A 添加Json对象B</span></span><br><span class="line">    <span class="built_in">cJSON_AddItemToArray</span>(body, list = <span class="built_in">cJSON_CreateObject</span>());</span><br><span class="line">    <span class="comment">// 在json对象B中添加键值对: &quot;name&quot;:&quot;luffy&quot;</span></span><br><span class="line">    <span class="built_in">cJSON_AddStringToObject</span>(list,<span class="string">&quot;name&quot;</span>,<span class="string">&quot;luffy&quot;</span>);</span><br><span class="line">    <span class="comment">// 在json对象B中添加键值对: &quot;age&quot;:19</span></span><br><span class="line">    <span class="built_in">cJSON_AddNumberToObject</span>(list,<span class="string">&quot;age&quot;</span>,<span class="number">19</span>);</span><br><span class="line"> </span><br><span class="line">    <span class="comment">// char *s = cJSON_Print(root);</span></span><br><span class="line">    <span class="keyword">char</span> *s = <span class="built_in">cJSON_PrintUnformatted</span>(root);</span><br><span class="line">    <span class="keyword">if</span>(s)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot; %s \n&quot;</span>,s);</span><br><span class="line">        <span class="built_in">free</span>(s);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span>(root)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="built_in">cJSON_Delete</span>(root); </span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>运行结果:</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">&#123;&quot;person&quot;:[&#123;&quot;name&quot;:&quot;luffy&quot;,&quot;age&quot;:19&#125;]&#125;</span><br></pre></td></tr></table></figure>

<h2 id="4-解析-Json-字符串"><a href="#4-解析-Json-字符串" class="headerlink" title="4. 解析 Json 字符串"></a>4. 解析 Json 字符串</h2><h3 id="4-1-解析-Json-对象"><a href="#4-1-解析-Json-对象" class="headerlink" title="4.1 解析 Json 对象"></a>4.1 解析 Json 对象</h3><p>Json 字符串的解析流程和数据的封装流程相反，假设我们有这样一个 Json 字符串（字符串中的双引号需要通过转义字符将其转译为普通字符）：</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">&#123;\&quot;name\&quot;:\&quot;luffy\&quot;,\&quot;sex\&quot;:\&quot;man\&quot;,\&quot;age\&quot;:19&#125;</span><br></pre></td></tr></table></figure>

<p>示例代码如下：</p>
<figure class="highlight cpp"><table><tr><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;stdlib.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;string.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&quot;cJSON.h&quot;</span></span></span><br><span class="line"> </span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    cJSON *json, *name, *sex, *age;</span><br><span class="line">    <span class="keyword">char</span>* out=<span class="string">&quot;&#123;\&quot;name\&quot;:\&quot;luffy\&quot;,\&quot;sex\&quot;:\&quot;man\&quot;,\&quot;age\&quot;:19&#125;&quot;</span>;</span><br><span class="line"> </span><br><span class="line">    json = <span class="built_in">cJSON_Parse</span>(out); <span class="comment">//解析成json形式</span></span><br><span class="line">    name = <span class="built_in">cJSON_GetObjectItem</span>(json, <span class="string">&quot;name&quot;</span>);  <span class="comment">//获取键值内容</span></span><br><span class="line">    sex = <span class="built_in">cJSON_GetObjectItem</span>(json, <span class="string">&quot;sex&quot;</span>);</span><br><span class="line">    age = <span class="built_in">cJSON_GetObjectItem</span>(json, <span class="string">&quot;age&quot;</span>);</span><br><span class="line"> </span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;name:%s,sex:%s,age:%d\n&quot;</span>, name-&gt;valuestring, sex-&gt;valuestring, age-&gt;valueint);</span><br><span class="line"> </span><br><span class="line">    <span class="built_in">cJSON_Delete</span>(json);  <span class="comment">//释放内存 </span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>输出的结果:</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">name:luffy,sex:man,age:19</span><br></pre></td></tr></table></figure>

<p><strong>如果是在严格的场所，应该先判定每个 item 的 type，然后再考虑去取值</strong>。</p>
<h3 id="4-2-解析嵌套的-Json-对象"><a href="#4-2-解析嵌套的-Json-对象" class="headerlink" title="4.2 解析嵌套的 Json 对象"></a>4.2 解析嵌套的 Json 对象</h3><p>加大一点难度，下面我们解析一个嵌套的 Json 对象，数据如下：</p>
<figure class="highlight cpp"><table><tr><td class="code"><pre><span class="line">&#123;\<span class="string">&quot;list\&quot;:&#123;\&quot;name\&quot;:\&quot;luffy\&quot;,\&quot;age\&quot;:19&#125;,\&quot;other\&quot;:&#123;\&quot;name\&quot;:\&quot;ace\&quot;&#125;&#125;</span></span><br><span class="line"><span class="string">int main()</span></span><br><span class="line"><span class="string">&#123;</span></span><br><span class="line"><span class="string">    char *s = &quot;</span>&#123;\<span class="string">&quot;list\&quot;:&#123;\&quot;name\&quot;:\&quot;luffy\&quot;,\&quot;age\&quot;:19&#125;,\&quot;other\&quot;:&#123;\&quot;name\&quot;:\&quot;ace\&quot;&#125;&#125;&quot;</span>;</span><br><span class="line">    cJSON *root = <span class="built_in">cJSON_Parse</span>(s);</span><br><span class="line">    <span class="keyword">if</span>(!root) </span><br><span class="line">    &#123;</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;get root faild !\n&quot;</span>);</span><br><span class="line">        <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    cJSON *js_list = <span class="built_in">cJSON_GetObjectItem</span>(root, <span class="string">&quot;list&quot;</span>);</span><br><span class="line">    <span class="keyword">if</span>(!js_list) </span><br><span class="line">    &#123;</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;no list!\n&quot;</span>);</span><br><span class="line">        <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;list type is %d\n&quot;</span>,js_list-&gt;type);</span><br><span class="line"></span><br><span class="line">    cJSON *name = <span class="built_in">cJSON_GetObjectItem</span>(js_list, <span class="string">&quot;name&quot;</span>);</span><br><span class="line">    <span class="keyword">if</span>(!name) </span><br><span class="line">    &#123;</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;No name !\n&quot;</span>);</span><br><span class="line">        <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;name type is %d\n&quot;</span>,name-&gt;type);</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;name is %s\n&quot;</span>,name-&gt;valuestring);</span><br><span class="line"></span><br><span class="line">    cJSON *age = <span class="built_in">cJSON_GetObjectItem</span>(js_list, <span class="string">&quot;age&quot;</span>);</span><br><span class="line">    <span class="keyword">if</span>(!age) </span><br><span class="line">    &#123;</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;no age!\n&quot;</span>);</span><br><span class="line">        <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;age type is %d\n&quot;</span>, age-&gt;type);</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;age is %d\n&quot;</span>,age-&gt;valueint);</span><br><span class="line"></span><br><span class="line">    cJSON *js_other = <span class="built_in">cJSON_GetObjectItem</span>(root, <span class="string">&quot;other&quot;</span>);</span><br><span class="line">    <span class="keyword">if</span>(!js_other) </span><br><span class="line">    &#123;</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;no list!\n&quot;</span>);</span><br><span class="line">        <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;list type is %d\n&quot;</span>,js_other-&gt;type);</span><br><span class="line"></span><br><span class="line">    cJSON *js_name = <span class="built_in">cJSON_GetObjectItem</span>(js_other, <span class="string">&quot;name&quot;</span>);</span><br><span class="line">    <span class="keyword">if</span>(!js_name) </span><br><span class="line">    &#123;</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;No name !\n&quot;</span>);</span><br><span class="line">        <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;name type is %d\n&quot;</span>,js_name-&gt;type);</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;name is %s\n&quot;</span>,js_name-&gt;valuestring);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span>(root)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="built_in">cJSON_Delete</span>(root);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>打印结果:</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">list type is 6</span><br><span class="line">name type is 4</span><br><span class="line">name is luffy</span><br><span class="line">age type is 3</span><br><span class="line">age is 19</span><br><span class="line">list type is 6</span><br><span class="line">name type is 4</span><br><span class="line">name is ace</span><br></pre></td></tr></table></figure>

<h3 id="4-3-解析-Json-数组"><a href="#4-3-解析-Json-数组" class="headerlink" title="4.3 解析 Json 数组"></a>4.3 解析 Json 数组</h3><p>如果我们遇到的 Json 字符串是一个 Json 数组格式，处理方式和 Json 对象差不多，比如我们要解析如下字符串：</p>
<figure class="highlight cpp"><table><tr><td class="code"><pre><span class="line">&#123;\<span class="string">&quot;names\&quot;:[\&quot;luffy\&quot;,\&quot;robin\&quot;]&#125;</span></span><br><span class="line"><span class="string">int main(int argc, char **argv)</span></span><br><span class="line"><span class="string">&#123;</span></span><br><span class="line"><span class="string">    char *s = &quot;</span>&#123;\<span class="string">&quot;names\&quot;:[\&quot;luffy\&quot;,\&quot;robin\&quot;]&#125;&quot;</span>;</span><br><span class="line">    cJSON *root = <span class="built_in">cJSON_Parse</span>(s);</span><br><span class="line">    <span class="keyword">if</span>(!root) </span><br><span class="line">    &#123;</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;get root faild !\n&quot;</span>);</span><br><span class="line">        <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    cJSON *js_list = <span class="built_in">cJSON_GetObjectItem</span>(root, <span class="string">&quot;names&quot;</span>);</span><br><span class="line">    <span class="keyword">if</span>(!js_list)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;no list!\n&quot;</span>);</span><br><span class="line">        <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">int</span> array_size = <span class="built_in">cJSON_GetArraySize</span>(js_list);</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;array size is %d\n&quot;</span>,array_size);</span><br><span class="line">    <span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">0</span>; i&lt; array_size; i++) </span><br><span class="line">    &#123;</span><br><span class="line">        cJSON *item = <span class="built_in">cJSON_GetArrayItem</span>(js_list, i);</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;item type is %d\n&quot;</span>,item-&gt;type);</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;%s\n&quot;</span>,item-&gt;valuestring);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span>(root)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="built_in">cJSON_Delete</span>(root);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="4-4-解析嵌套的-Json-对象和数组"><a href="#4-4-解析嵌套的-Json-对象和数组" class="headerlink" title="4.4 解析嵌套的 Json 对象和数组"></a>4.4 解析嵌套的 Json 对象和数组</h3><p>对于 Json 字符串最复杂的个数莫过于 Json 对象和 Json 数组嵌套的形式，下面通过一个例子演示一下应该如何解析，字符串格式如下：</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">&#123;\&quot;list\&quot;:[&#123;\&quot;name\&quot;:\&quot;luffy\&quot;,\&quot;age\&quot;:19&#125;,&#123;\&quot;name\&quot;:\&quot;sabo\&quot;,\&quot;age\&quot;:21&#125;]&#125;</span><br></pre></td></tr></table></figure>

<p>在解析的时候，我们只需要按照从属关系，一层层解析即可：</p>
<ul>
<li>根节点是一个 Json 对象，基于根节点中的 key 值取出对应的 value 值，得到一个 Json 数组</li>
<li>读出 Json 数组的大小，遍历里边的各个元素，每个元素都是一个 Json 对象</li>
<li>将 Json 对象中的键值对根据 key 值取出对应的 value 值</li>
<li>从取出的 Value 值中读出实际类型对应的数值 示例代码如下：</li>
</ul>
<figure class="highlight cpp"><table><tr><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&quot;cJSON.h&quot;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;stdlib.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">(<span class="keyword">int</span> argc, <span class="keyword">char</span> **argv)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">char</span> *s = <span class="string">&quot;&#123;\&quot;list\&quot;:[&#123;\&quot;name\&quot;:\&quot;luffy\&quot;,\&quot;age\&quot;:19&#125;,&#123;\&quot;name\&quot;:\&quot;sabo\&quot;,\&quot;age\&quot;:21&#125;]&#125;&quot;</span>;</span><br><span class="line">    cJSON *root = <span class="built_in">cJSON_Parse</span>(s);</span><br><span class="line">    <span class="keyword">if</span>(!root) </span><br><span class="line">    &#123;</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;get root faild !\n&quot;</span>);</span><br><span class="line">        <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    cJSON *list = <span class="built_in">cJSON_GetObjectItem</span>(root, <span class="string">&quot;list&quot;</span>);</span><br><span class="line">    <span class="keyword">if</span>(!list)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;no list!\n&quot;</span>);</span><br><span class="line">        <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">int</span> array_size = <span class="built_in">cJSON_GetArraySize</span>(list);</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;array size is %d\n&quot;</span>,array_size);</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">0</span>; i&lt; array_size; i++) </span><br><span class="line">    &#123;</span><br><span class="line">        cJSON* item = <span class="built_in">cJSON_GetArrayItem</span>(list, i);</span><br><span class="line">        cJSON* name = <span class="built_in">cJSON_GetObjectItem</span>(item, <span class="string">&quot;name&quot;</span>);</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;name is %s\n&quot;</span>,name-&gt;valuestring);</span><br><span class="line">        cJSON* age = <span class="built_in">cJSON_GetObjectItem</span>(item, <span class="string">&quot;age&quot;</span>);</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;age is %d\n&quot;</span>,age-&gt;valueint);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span>(root)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="built_in">cJSON_Delete</span>(root);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>文章链接：<a target="_blank" rel="noopener" href="https://subingwen.cn/c/cjson%E4%BD%BF%E7%94%A8/">https://subingwen.cn/c/cjson%E4%BD%BF%E7%94%A8/</a></p>
</blockquote>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">逝水无痕</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://hexo.zyjblogs.cn/posts/c++/library/json/1.html">https://hexo.zyjblogs.cn/posts/c++/library/json/1.html</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://hexo.zyjblogs.cn" target="_blank">逝水无痕の博客</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/c/">c++</a><a class="post-meta__tags" href="/tags/cJson/">cJson</a></div><div class="post_share"><div class="social-share" data-image="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/posts/c++/base/virtual/1.html"><img class="prev-cover" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">虚基类</div></div></a></div><div class="next-post pull-right"><a href="/posts/c++/study/backend/1.html"><img class="next-cover" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">C++后台</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span> 相关推荐</span></div><div class="relatedPosts-list"><div><a href="/posts/books/c/1.html" title="C++书单"><img class="cover" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-08-09</div><div class="title">C++书单</div></div></a></div><div><a href="/posts/c++/base/polymorphic/1.html" title="C++编译期多态与运行期多态"><img class="cover" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-02-07</div><div class="title">C++编译期多态与运行期多态</div></div></a></div><div><a href="/posts/c++/base/virtual/1.html" title="虚基类"><img class="cover" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-02-07</div><div class="title">虚基类</div></div></a></div><div><a href="/posts/c++/study/backend/1.html" title="C++后台"><img class="cover" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-02-07</div><div class="title">C++后台</div></div></a></div><div><a href="/posts/c++/library/date/1.html" title="C++ 使用 chrono 库处理日期和时间"><img class="cover" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-02-07</div><div class="title">C++ 使用 chrono 库处理日期和时间</div></div></a></div><div><a href="/posts/c++/article/2022/02/07/1.html" title="C++ 八股文（一）"><img class="cover" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-02-07</div><div class="title">C++ 八股文（一）</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="https://zyjblogs.cn/logo.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">逝水无痕</div><div class="author-info__description"></div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">11</div></a></div><div class="card-info-data-item is-center"><a href="/tags/"><div class="headline">标签</div><div class="length-num">8</div></a></div><div class="card-info-data-item is-center"><a href="/categories/"><div class="headline">分类</div><div class="length-num">5</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/zyjnicemoe"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/zyjnicemoe" target="_blank" title="Github"><i class="fab fa-github"></i></a><a class="social-icon" href="mailto:1317453947@qq.com" target="_blank" title="Email"><i class="fas fa-envelope"></i></a><a class="social-icon" href="/atom.xml" target="_blank" title=""><i class="fas fa-rss"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>公告</span></div><div class="announcement_content"><a target="_blank" rel="noopener" href="https://zyjblogs.cn">逝水无痕の博客https://zyjblogs.cn迁移到此</a></div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#C-C-%E5%85%B3%E4%BA%8E-cJson-%E5%BA%93%E7%9A%84%E4%BD%BF%E7%94%A8"><span class="toc-number">1.</span> <span class="toc-text">C&#x2F;C++ 关于 cJson 库的使用</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1-cJSON-%E7%BB%93%E6%9E%84%E4%BD%93"><span class="toc-number">1.1.</span> <span class="toc-text">1. cJSON 结构体</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2-cJson-API"><span class="toc-number">1.2.</span> <span class="toc-text">2. cJson API</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#2-1-%E6%95%B0%E6%8D%AE%E7%9A%84%E5%B0%81%E8%A3%85"><span class="toc-number">1.2.1.</span> <span class="toc-text">2.1 数据的封装</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-2-Json-%E5%AF%B9%E8%B1%A1%E6%93%8D%E4%BD%9C"><span class="toc-number">1.2.2.</span> <span class="toc-text">2.2 Json 对象操作</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-3-Json-%E6%95%B0%E7%BB%84%E6%93%8D%E4%BD%9C"><span class="toc-number">1.2.3.</span> <span class="toc-text">2.3 Json 数组操作</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-4-%E5%BA%8F%E5%88%97%E5%8C%96"><span class="toc-number">1.2.4.</span> <span class="toc-text">2.4 序列化</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-5-Json-%E5%AD%97%E7%AC%A6%E4%B8%B2%E7%9A%84%E8%A7%A3%E6%9E%90"><span class="toc-number">1.2.5.</span> <span class="toc-text">2.5 Json 字符串的解析</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-6-%E5%86%85%E5%AD%98%E9%87%8A%E6%94%BE"><span class="toc-number">1.2.6.</span> <span class="toc-text">2.6 内存释放</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-Json-%E6%95%B0%E6%8D%AE%E7%9A%84%E5%B0%81%E8%A3%85"><span class="toc-number">1.3.</span> <span class="toc-text">3. Json 数据的封装</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#3-1-Json-%E5%AF%B9%E8%B1%A1%E6%93%8D%E4%BD%9C%E4%B8%BE%E4%BE%8B"><span class="toc-number">1.3.1.</span> <span class="toc-text">3.1 Json 对象操作举例</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-2-Json-%E6%95%B0%E7%BB%84%E6%93%8D%E4%BD%9C%E4%B8%BE%E4%BE%8B"><span class="toc-number">1.3.2.</span> <span class="toc-text">3.2 Json 数组操作举例</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-3-Json-%E5%AF%B9%E8%B1%A1%E3%80%81%E6%95%B0%E7%BB%84%E5%B5%8C%E5%A5%97%E4%BD%BF%E7%94%A8"><span class="toc-number">1.3.3.</span> <span class="toc-text">3.3 Json 对象、数组嵌套使用</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#4-%E8%A7%A3%E6%9E%90-Json-%E5%AD%97%E7%AC%A6%E4%B8%B2"><span class="toc-number">1.4.</span> <span class="toc-text">4. 解析 Json 字符串</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#4-1-%E8%A7%A3%E6%9E%90-Json-%E5%AF%B9%E8%B1%A1"><span class="toc-number">1.4.1.</span> <span class="toc-text">4.1 解析 Json 对象</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-2-%E8%A7%A3%E6%9E%90%E5%B5%8C%E5%A5%97%E7%9A%84-Json-%E5%AF%B9%E8%B1%A1"><span class="toc-number">1.4.2.</span> <span class="toc-text">4.2 解析嵌套的 Json 对象</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-3-%E8%A7%A3%E6%9E%90-Json-%E6%95%B0%E7%BB%84"><span class="toc-number">1.4.3.</span> <span class="toc-text">4.3 解析 Json 数组</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-4-%E8%A7%A3%E6%9E%90%E5%B5%8C%E5%A5%97%E7%9A%84-Json-%E5%AF%B9%E8%B1%A1%E5%92%8C%E6%95%B0%E7%BB%84"><span class="toc-number">1.4.4.</span> <span class="toc-text">4.4 解析嵌套的 Json 对象和数组</span></a></li></ol></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/posts/c++/base/polymorphic/1.html" title="C++编译期多态与运行期多态"><img src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="C++编译期多态与运行期多态"/></a><div class="content"><a class="title" href="/posts/c++/base/polymorphic/1.html" title="C++编译期多态与运行期多态">C++编译期多态与运行期多态</a><time datetime="2022-02-06T16:00:00.000Z" title="发表于 2022-02-07 00:00:00">2022-02-07</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/posts/c++/base/virtual/1.html" title="虚基类"><img src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="虚基类"/></a><div class="content"><a class="title" href="/posts/c++/base/virtual/1.html" title="虚基类">虚基类</a><time datetime="2022-02-06T16:00:00.000Z" title="发表于 2022-02-07 00:00:00">2022-02-07</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/posts/c++/library/json/1.html" title="C/C++ 关于 cJson 库的使用"><img src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="C/C++ 关于 cJson 库的使用"/></a><div class="content"><a class="title" href="/posts/c++/library/json/1.html" title="C/C++ 关于 cJson 库的使用">C/C++ 关于 cJson 库的使用</a><time datetime="2022-02-06T16:00:00.000Z" title="发表于 2022-02-07 00:00:00">2022-02-07</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/posts/c++/study/backend/1.html" title="C++后台"><img src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="C++后台"/></a><div class="content"><a class="title" href="/posts/c++/study/backend/1.html" title="C++后台">C++后台</a><time datetime="2022-02-06T16:00:00.000Z" title="发表于 2022-02-07 00:00:00">2022-02-07</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/posts/c++/library/date/1.html" title="C++ 使用 chrono 库处理日期和时间"><img src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="C++ 使用 chrono 库处理日期和时间"/></a><div class="content"><a class="title" href="/posts/c++/library/date/1.html" title="C++ 使用 chrono 库处理日期和时间">C++ 使用 chrono 库处理日期和时间</a><time datetime="2022-02-06T16:00:00.000Z" title="发表于 2022-02-07 00:00:00">2022-02-07</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2019 - 2022 By 逝水无痕</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text"><div><img style="padding-top:2px" src="https://sp-ao.shortpixel.ai/client/q_glossy,ret_img/https://zyjblogs.cn/img/icp.png"><a class="banquan" style="color:#000" href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=鄂ICP备19023232号" target="_blank" data-pjax-state="">鄂ICP备19023232号</a></div></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><div class="search-dialog__title" id="local-search-title">本地搜索</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div></div><hr/><div id="local-search-results"></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><script src="/js/search/local-search.js"></script><script>var preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',preloader.endLoading())</script><div class="js-pjax"></div><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/activate-power-mode.min.js"></script><script>POWERMODE.colorful = true;
POWERMODE.shake = true;
POWERMODE.mobile = false;
document.body.addEventListener('input', POWERMODE);
</script><script src="https://cdn.jsdelivr.net/npm/pjax/pjax.min.js"></script><script>let pjaxSelectors = [
  'title',
  '#config-diff',
  '#body-wrap',
  '#rightside-config-hide',
  '#rightside-config-show',
  '.js-pjax'
]

if (false) {
  pjaxSelectors.unshift('meta[property="og:image"]', 'meta[property="og:title"]', 'meta[property="og:url"]')
}

var pjax = new Pjax({
  elements: 'a:not([target="_blank"]):not([href="/music/"]):not([href="/no-pjax/"])',
  selectors: pjaxSelectors,
  cacheBust: false,
  analytics: false,
  scrollRestoration: false
})

document.addEventListener('pjax:send', function () {

  // removeEventListener scroll 
  window.removeEventListener('scroll', window.tocScrollFn)
  window.removeEventListener('scroll', scrollCollect)

  typeof preloader === 'object' && preloader.initLoading()
  
  if (window.aplayers) {
    for (let i = 0; i < window.aplayers.length; i++) {
      if (!window.aplayers[i].options.fixed) {
        window.aplayers[i].destroy()
      }
    }
  }

  typeof typed === 'object' && typed.destroy()

  //reset readmode
  const $bodyClassList = document.body.classList
  $bodyClassList.contains('read-mode') && $bodyClassList.remove('read-mode')

})

document.addEventListener('pjax:complete', function () {
  window.refreshFn()

  document.querySelectorAll('script[data-pjax]').forEach(item => {
    const newScript = document.createElement('script')
    const content = item.text || item.textContent || item.innerHTML || ""
    Array.from(item.attributes).forEach(attr => newScript.setAttribute(attr.name, attr.value))
    newScript.appendChild(document.createTextNode(content))
    item.parentNode.replaceChild(newScript, item)
  })

  GLOBAL_CONFIG.islazyload && window.lazyLoadInstance.update()

  typeof chatBtnFn === 'function' && chatBtnFn()
  typeof panguInit === 'function' && panguInit()

  // google analytics
  typeof gtag === 'function' && gtag('config', '', {'page_path': window.location.pathname});

  // baidu analytics
  typeof _hmt === 'object' && _hmt.push(['_trackPageview',window.location.pathname]);

  typeof loadMeting === 'function' && document.getElementsByClassName('aplayer').length && loadMeting()

  // Analytics
  if (false) {
    MtaH5.pgv()
  }

  // prismjs
  typeof Prism === 'object' && Prism.highlightAll()

  typeof preloader === 'object' && preloader.endLoading()
})

document.addEventListener('pjax:error', (e) => {
  if (e.request.status === 404) {
    pjax.loadUrl('/404.html')
  }
})</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>